package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 定时任务类 定时处理订单状态
 */
@Component
@Slf4j
public class OrderTask {

    private final OrderMapper orderMapper;

    public OrderTask(OrderMapper orderMapper) {
        this.orderMapper = orderMapper;
    }

    /**
     * 处理订单超时的方法
     */
    @Scheduled(cron = "0 * * * * ? ") //每分钟执行一次
    public void processTimeoutOrder() {
        log.info("定时处理订单超时:{}", LocalDateTime.now());
        //订单超时产查询订单 (当前时间-15分钟)
        List<Orders> list = orderMapper.getByStatusAndOrderTimeLT(Orders.PENDING_PAYMENT, LocalDateTime.now().plusMinutes(-15));
        //不等于空
        if (list != null && !list.isEmpty()) {
            list.forEach(orders -> {
                orders.setStatus(Orders.CANCELLED); //设置订单状态
                orders.setCancelReason("订单超时，订单取消"); //取消原因
                orders.setCancelTime(LocalDateTime.now()); //取消时间
                orderMapper.update(orders); //修改
            });
        }
    }


    /**
     * 处理一直处于派送中的订单 自动修改成完成
     */
    @Scheduled(cron = "0 0 1 * * ?") //每天凌晨一点触发一次
    public void processDeliverOrder() {
        log.info("定时处理订单派送中:{}", LocalDateTime.now());

        List<Orders> orders = orderMapper.getByStatusAndOrderTimeLT(Orders.DELIVERY_IN_PROGRESS, LocalDateTime.now().plusMinutes(-60));
        //不等于空
        if (orders != null && !orders.isEmpty()) {
            orders.forEach(order -> {
                order.setStatus(Orders.COMPLETED); //设置订单状态
                orderMapper.update(order); //修改
            });
        }
    }
}
